﻿
using Base.Common.Entity;
using hlog;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Net;
using System.Text;
namespace Base.Common.HttpClient
{
    public class HttpRequest {
        static HttpRequest(){
              ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
        }
    public static String httpGet( String url)
        {
         
                 String res = "";
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                request.Timeout = 5000;
                request.Method = "GET";
                request.ContentType = "text/json";//链接类型
                request.KeepAlive = false;
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                using( Stream s = response.GetResponseStream() ) {
                    StreamReader reader = new StreamReader(s ,Encoding.UTF8);
                    res= reader.ReadToEnd();
                }
                if( BaseConfig.httpClientLog ) {
                    HttpClientLog log = new HttpClientLog();
                    log.url = url;
                    log.result = res;
                GuidangCache.addLog(log);
            }
                return res;
           
        }
        public static String httpPost( String url, string str)
        {
            HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
            req.Method = "POST";
            req.ContentType = "application/json";
            req.Accept = "*/*";
            req.UserAgent = "sgj";
            req.Headers.Add("cache-control" ,"no-cache");
            req.ServicePoint.Expect100Continue = false;
            byte[] data = Encoding.UTF8.GetBytes(str);//把字符串转换为字节
            req.ContentLength = data.Length; //请求长度
            using (Stream reqStream = req.GetRequestStream()) //获取
            {
                reqStream.Write(data, 0, data.Length);//向当前流中写入字节
                reqStream.Flush();
                reqStream.Close(); //关闭当前流
            }
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); //响应结果
            Stream stream = resp.GetResponseStream();
            //获取响应内容
            String res = "";
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                res= reader.ReadToEnd();
            }
            if( BaseConfig.httpClientLog ) {
                HttpClientLog log = new HttpClientLog();
                log.url = url;
                log.param = str;
                log.result = res;
                GuidangCache.addLog(log);
            }
            return res;
        }
    }
}
